const Inquirer = require('inquirer');
const { fetchRepoList, fetchTag } = require('./requst');
const { wrapLoading } = require('./utils');
const util = require('util');
let downloadGitRepo = require('download-git-repo');
downloadGitRepo = util.promisify(downloadGitRepo);
const path = require('path');
class Creator {
    constructor(projectName, targetDir){
        console.log('Creator', projectName, targetDir);
        this.projectName = projectName;
        this.targetDir = targetDir;
        this.userName = 'gmzd2008'
    }
    async fetchRepo (userName) {
        let repos = await wrapLoading(fetchRepoList,'查询模版库列表',this.userName);
        // console.log('repos', repos);
        return repos;
    }
    async fetchTag (repo) {
        let tags = await wrapLoading(fetchTag, '查询选中库的版本列表', this.userName, repo);
        // console.log('tags', tags);
        return tags;
    }
    downloadLocal = async (repo, version) => {
        let registry = 'gmzd2008'
        let api = `${registry}/${repo}`;
        if (version) {
          api += `#${version}`;
        }
        await wrapLoading(downloadGitRepo, '下载模...',api, path.resolve(this.targetDir,`${repo}@${version}`));
        return true;
      };
    async create() {
        // 真实创建项目
        // 1> 获取目标组织下的模版
        let repos = await this.fetchRepo();
        if(!repos) return;
        repos = repos.map(item=>item.name)
        // console.log('repos filter', repos);
        let {repo} = await Inquirer.prompt({
            name: 'repo',
            type: 'list',
            choices: repos,
            message: 'please choose a template to create project'
        })
        if(!repo) return;
        // 2> 通过模版查找模版版本号
        let tags = await this.fetchTag(repo);
        if(!tags) return;
        tags = tags.map(item=>item.name)
        let {tag} = await Inquirer.prompt({
            name: 'tag',
            type: 'list',
            choices: tags,
            message: 'please choose a template version to create project'
        })
        console.log('选择的version', tag)
        // 3> 下载模版
        let download = await this.downloadLocal(repo,tag)
        // 4> 根据用户的选项，合成具体项目模版
    }
}

module.exports = Creator;